package com.pokermind.dse.tcp.client.interactive;

import java.util.List;

/**
 * 界面渲染（交互式客户端UI）- 紧凑版
 * 
 * @author PokerMind Interactive Client
 */
public class UIRenderer {
    
    /**
     * 清屏
     */
    public static void clearScreen() {
        System.out.print("\033[H\033[2J");
        System.out.flush();
    }
    
    /**
     * 渲染完整游戏界面（紧凑版，V4.26：不清屏，保留历史日志）
     */
    public static void render(GameState state) {
        System.out.println(); // 添加空行分隔
        printCompactView(state);
    }
    
    /**
     * 紧凑视图
     */
    private static void printCompactView(GameState state) {
        // 头部信息（单行，使用中文）
        System.out.printf("━━━ PokerMind ━━━ 牌局: %s │ %s │ 底池: %d ━━━%n",
                state.getHandId() != null ? state.getHandId() : "N/A",
                getStreetChinese(state.getStreet()),
                state.getPot());
        
        // 玩家状态（紧凑表格）
        Player currentPlayer = state.getCurrentPlayer();
        for (Player player : state.getPlayers()) {
            boolean isCurrent = player.equals(currentPlayer);
            String marker = isCurrent ? "▶" : " ";
            String status = getCompactStatus(player.getStatus());
            
            // 格式：▶ SB  10000  [行动]  100  │ As Kd
            String line = String.format("%s %-3s %6d %-6s %4d",
                    marker,
                    player.getPosition(),
                    player.getStack(),
                    status,
                    player.getCurrentBet());
            
            // 当前玩家显示底牌
            if (isCurrent && player.getHoleCards() != null && !player.getHoleCards().isEmpty()) {
                line += "  │ " + player.getHoleCards();
            }
            
            System.out.println(line);
        }
        
        // 公共牌（单行）
        if (!state.getBoard().isEmpty()) {
            System.out.println("Board: " + String.join(" ", state.getBoard()));
        }
        
        // 行动历史（压缩）
        printCompactHistory(state);
        
        // 当前选项
        printCompactOptions(state);
    }
    
    /**
     * 紧凑的行动历史（V4.24优化：显示完整行动和金额）
     */
    private static void printCompactHistory(GameState state) {
        List<GameState.ActionRecord> history = state.getActionHistory();
        if (history.isEmpty()) {
            return;
        }
        
        System.out.print("行动: ");
        
        String currentStreet = "";
        StringBuilder line = new StringBuilder();
        
        for (GameState.ActionRecord record : history) {
            if (!record.getStreet().equals(currentStreet)) {
                if (line.length() > 0) {
                    System.out.print(line + " │ ");
                    line = new StringBuilder();
                }
                currentStreet = record.getStreet();
            }
            
            Player player = state.getPlayerByUserId(record.getUserId());
            String pos = player != null ? player.getPosition() : "?";
            String action = getActionChinese(record.getAction());
            
            // 显示：位置-行动-金额
            line.append(pos).append("-").append(action);
            if (record.getAmount() > 0) {
                line.append(record.getAmount());
            }
            line.append(" ");
        }
        
        if (line.length() > 0) {
            System.out.print(line);
        }
        System.out.println();
    }
    
    /**
     * 紧凑的选项提示
     */
    private static void printCompactOptions(GameState state) {
        Player currentPlayer = state.getCurrentPlayer();
        if (currentPlayer == null) {
            return;
        }
        
        // 计算需跟注金额
        int maxBet = state.getPlayers().stream()
                .mapToInt(Player::getCurrentBet)
                .max()
                .orElse(0);
        int toCall = maxBet - currentPlayer.getCurrentBet();
        int minRaise = maxBet + state.getBigBlind();
        
        System.out.println("─".repeat(60));
        System.out.printf("需跟注: %d │ 最小加注: %d%n", toCall, minRaise);
    }
    
    /**
     * 打印AI决策和脚本预设对比
     */
    public static void printDecisionComparison(
            String aiAction, String aiSize, String aiReasons, double aiConfidence,
            String scriptAction, int scriptAmount, String scriptReasoning) {
        System.out.println();
        // V4.24: 简化显示，移除理由
        String sizeStr = "";
        if (aiSize != null && !aiSize.isEmpty() && !"0".equals(aiSize) && !"null".equals(aiSize)) {
            sizeStr = " " + aiSize;
        }
        System.out.printf("[建议] %s%s (%.0f%%)%n",
                aiAction.toUpperCase(),
                sizeStr,
                aiConfidence * 100);
        System.out.printf("[脚本] %s %s - %s%n",
                scriptAction.toUpperCase(),
                scriptAmount > 0 ? scriptAmount : "",
                scriptReasoning);
        System.out.println("\n[1]AI [2]脚本 [3]自动 [0]退出");
        System.out.print("> ");
    }
    
    /**
     * 打印AI决策（V4.28纯AI模式）
     */
    public static void printAIDecision(String action, String size, String reasons, double confidence) {
        System.out.println();
        String sizeStr = "";
        if (size != null && !size.isEmpty() && !"0".equals(size) && !"null".equals(size)) {
            sizeStr = " " + size;
        }
        System.out.printf("[AI建议] %s%s (%.0f%%)%n",
                action.toUpperCase(),
                sizeStr,
                confidence * 100);
    }
    
    /**
     * 打印最终结果
     */
    public static void printFinalResult(GameState state) {
        System.out.println("\n━━━ 手牌结束 ━━━");
        System.out.println("Pot: " + state.getPot());
        
        for (Player player : state.getPlayers()) {
            System.out.printf("%s: %d (%s)%n",
                    player.getPosition(),
                    player.getStack(),
                    getCompactStatus(player.getStatus()));
        }
        System.out.println("━".repeat(40));
    }
    
    /**
     * 紧凑的状态显示
     */
    private static String getCompactStatus(Player.PlayerStatus status) {
        return switch (status) {
            case ACTIVE -> "[行动]";
            case FOLDED -> "[弃牌]";
            case ALL_IN -> "[AI]";
            case WAITING -> "[等待]";
        };
    }
    
    /**
     * 缩短Hand ID（只显示后6位）
     */
    private static String shortHandId(String handId) {
        if (handId == null || handId.length() <= 6) {
            return handId != null ? handId : "N/A";
        }
        return "..." + handId.substring(handId.length() - 6);
    }
    
    /**
     * 街道名称中文转换
     */
    private static String getStreetChinese(String street) {
        if (street == null) return "未知";
        return switch (street.toLowerCase()) {
            case "preflop" -> "翻前";
            case "flop" -> "翻牌圈";
            case "turn" -> "转牌圈";
            case "river" -> "河牌圈";
            default -> street.toUpperCase();
        };
    }
    
    /**
     * 行动名称中文转换（V4.24新增）
     */
    private static String getActionChinese(String action) {
        if (action == null) return "?";
        return switch (action.toLowerCase()) {
            case "fold" -> "弃";
            case "check" -> "过";
            case "call" -> "跟";
            case "raise", "bet" -> "加";
            case "all_in", "allin" -> "梭";
            default -> action.substring(0, 1).toUpperCase();
        };
    }
    
    /**
     * 缩短行动名称
     */
    private static String shortAction(String action) {
        return switch (action.toLowerCase()) {
            case "fold" -> "F";
            case "check" -> "X";
            case "call" -> "C";
            case "raise" -> "R";
            case "bet" -> "B";
            case "all_in", "allin" -> "AI";
            default -> action.substring(0, 1).toUpperCase();
        };
    }
}
